<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class MessageController extends Controller
{

    public function index(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'      => 'required|integer|min:1',
                'inform_time'  => 'date|before:'.date("Y-m-d H:i:s"),
                'inform_id'    => 'integer|min:1',
                'is_own'       => 'boolean',
                'is_unreplied' => 'boolean',
                'type'         => 'min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId      = $input["user_id"];
        $isOwn       = empty($input["is_own"])?false:true;
        $isUnReplied = empty($input["is_unreplied"])?false:true;
        $isNotcare   = (isset($input["type"]) && $input["type"] == "message")?1:0;

        //按本页最早通知时间查找上一页的通知
        $pageWhereStr   = !empty($input["inform_time"])?"AND im_inform.send_time <= '".$input["inform_time"]."'":"";
        $countLimit     = !empty($input["inform_time"])?16:15;
        //查找用户相关的通知
        $informResult = DB::select("SELECT im_inform.id AS inform_id,im_inform.title,im_inform.sender_id,im_inform.content,
            im_inform.send_count,im_inform.replied_count,im_inform.send_time,im_inform.is_closed,im_inform.close_time,im_inform.is_urgent,im_inform.is_notcare,
            im_inform_user.id,im_inform_user.special,im_inform_user.token,
            im_reply_opt.content AS reply_opt_content,
            im_user.id AS sender_id,im_set.name AS sender_name,im_set.icon AS sender_icon
            FROM im_inform
            LEFT JOIN im_inform_user ON im_inform_user.inform_id = im_inform.id AND im_inform_user.user_id = $userId
            LEFT JOIN im_reply_opt ON im_reply_opt.id = im_inform_user.reply_opt_id
            LEFT JOIN im_user ON im_user.id = im_inform.sender_id
            LEFT JOIN im_set ON im_set.id = im_inform.set_id
            WHERE 
            ".($isOwn?"im_inform.sender_id = $userId":"(im_inform_user.user_id = $userId ".($isUnReplied?"":"OR im_inform.sender_id = $userId").")")."
            AND im_inform.is_notcare = $isNotcare AND im_inform.is_sent = true AND im_inform.is_deleted = false "
            .($isUnReplied?"AND im_inform.is_closed = false AND im_inform_user.reply_opt_id is null":"")
            .($isUnReplied?"":" ".$pageWhereStr)
            ." ORDER BY im_inform.send_time DESC,im_inform.id DESC"
            .($isUnReplied?"":" LIMIT $countLimit")
            );

        //去除重复通知
        if(!empty($input["inform_id"])){
            $informReturn   = [];
            $startStore     = false;
            foreach ($informResult as $key => $value) {
                if($startStore){
                    $informReturn[] = $value;
                }
                if($startStore == false && $value->inform_id == $input["inform_id"]){
                    $startStore = true;
                }
            }
        }else{
            $informReturn = $informResult;
        }

        //查找回复项
        foreach ($informReturn as $key => $value) {
            $value->title            = $value->title.$value->special;
            $value->could_reply      = (empty($value->id) || $value->is_closed)?0:1;
            $value->is_own           = $value->sender_id == $userId?1:0;
            $value->inform_reply_opt = DB::table("im_reply_opt")
                ->select("id","content","is_expected","replied_count","url_page")
                ->where("inform_id",$value->inform_id)
                ->get();
        }

        return $this::jsonResponse(false,$informReturn);

    }

    public function count(Request $request)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'      => 'required|integer|min:1',
                'is_own'       => 'boolean',
                'is_unreplied' => 'boolean',
                'type'         => 'min:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $userId      = $input["user_id"];
        $isOwn       = empty($input["is_own"])?false:true;
        $isUnReplied = empty($input["is_unreplied"])?false:true;
        $isNotcare   = (isset($input["type"]) && $input["type"] == "message")?1:0;

        //查找用户相关的通知
        $informCountResult = DB::select("SELECT COUNT(im_inform.id) AS inform_count
            FROM im_inform
            LEFT JOIN im_inform_user ON im_inform_user.inform_id = im_inform.id AND im_inform_user.user_id = $userId
            WHERE ".($isOwn?"im_inform.sender_id = $userId":"(im_inform_user.user_id = $userId ".($isUnReplied?"":"OR im_inform.sender_id = $userId").")")."
            AND im_inform.is_notcare = $isNotcare AND im_inform.is_sent = true AND im_inform.is_deleted = false "
            .($isUnReplied?"AND im_inform.is_closed = false AND im_inform_user.reply_opt_id is null":""));

        return $this::jsonResponse(false,$informCountResult);

    }
}